const util = require('util');
const debug = util.debuglog('oil-game:exchangeEssence:dao');
const ExchangeFrom = require('./exchangeSchema');

//从Mongo中查询用户交易所表单信息
exports.getInitExChangeByMongo = function(uid){
  return new Promise(async (resolve, reject) => {
    ExchangeFrom.findOne({uid, type: 0}, function(err, data) {
      if(err) return reject(err);
      resolve(data);
    });
  });
}

//保存交易所信息
exports.saveExchangeFrom = function(exchange) {
  let {uid, id} = exchange;
  debug("uid = %s 保存交易信息 %s", uid, JSON.stringify(exchange));
  return new Promise((resolve, reject) => {
    //检测要保存的交易信息是否为空
    if(!exchange){ 
      debug("uid = %s 保存交易信息，检测到数据为空，即将返回 %s", uid, JSON.stringify(exchange));
      return reject({});
    }
    ExchangeFrom.findOne({id}, {_id: 1}, function(err,data){
      if(err){
        debug("uid = %s 查询交易信息数据异常 %s", uid, JSON.stringify(err));
        return reject(err);
      }
      if(data){   //更新文档
        ExchangeFrom.update({id}, exchange, function(err, data){
          if(err){
            debug("uid = %s 更新交易信息异常 %s", uid, JSON.stringify(err));
            return reject(err);
          }
          debug("uid = %s 更新交易数据成功 %s", uid, JSON.stringify(data));
          resolve(data);
        });
      }else{    //插入文档
        new ExchangeFrom(exchange).save((err, data)=> {
          if(err){
            debug("uid = %s 保存交易数据异常 %s", uid, JSON.stringify(err));
            return reject(err);
          }
          debug("uid = %s 保存交易数据成功 %s", uid, JSON.stringify(data));
          resolve(data);
        });
      }
    });
  });
}

//获取近三日交易所信息
exports.getHistoryTax = function(date1, date2, date3) {
  debug("date1 = %s date2 = %s date3 = %s 获取近三日交易所信息", date1, date2, date3);
  let mysqlClient = this.app.get('mysqlClient');
  let sql = `select date,price,exchange_id from _exchange_cream where date=? or date=? or date=?;`
  let args = [date1, date2, date3];
  return new Promise((resolve, reject) => {
    mysqlClient.query(sql, args, function (err, data) {
      if (err) {
        debug('获取近三日交易所信息异常 %s', JSON.stringify(err));
        return reject(err);
      }
      debug('获取近三日交易所信息成功 %s', JSON.stringify(data));
      let objRes = JSON.parse(JSON.stringify(data));
      resolve(Array.isArray(objRes) ? objRes : []);
    })
  });
}

//返回最新的N条交易完成数据
exports.getNowExchangeList = function(num){
  debug("num = %s 返回最新的N条交易完成数据", num);
  return new Promise(async (resolve, reject) => {
    ExchangeFrom.find({type: 1, oilNum: {$ne: 0}}, {oilNum: 1, money: 1, nickname: 1, _id: 0, updated_at: 1}).sort({updated_at: -1}).limit(num).exec(function(err, data) {
      if(err) {
        debug("num = %s 返回最新的N条交易完成数据异常 %s", num, JSON.stringify(err));
				return reject(err);
      }
      debug("num = %s 返回最新的N条交易完成数据 %s", num, JSON.stringify(data));
      resolve(data);
    });
  });
}
